package com.ytktt.study.week9.task3.rpcfx.lb;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 基于轮询的负载均衡算法
 *
 * @author ytk
 */
public class RoundRibbonLoadBalancer implements LoadBalancer {

    private final AtomicInteger roundRibbonNum;

    public RoundRibbonLoadBalancer(AtomicInteger roundRibbonNum) {
        this.roundRibbonNum = roundRibbonNum;
    }

    @Override
    public String select(List<String> urls) {
        long index = this.roundRibbonNum.getAndUpdate(cur -> (cur + 1) & 0x7FFFFFFF);
        return urls.get((int) (index % urls.size()));
    }
}
